import React, {
  createContext,
  ReactNode,
  useCallback,
  useState,
  useContext,
} from 'react';
import BasicsModal, {ModalType} from '../modal/BasicsModal';

type Props = {
  children: ReactNode;
};

export type AnimationType = 'fade' | 'none' | 'slide';

type State = {
  visible: boolean;
  params?: any;
  type?: ModalType;
  animationType?: AnimationType;
  onCallBack?: () => void;
};

type Value = {
  showModal: (
    modalType: ModalType,
    params?: any,
    animationType?: AnimationType,
  ) => void;
} & State;

const ModalContext = createContext<Value | undefined>(undefined);

const ModalProvider = function ({children}: Props): JSX.Element {
  const [state, setState] = useState<State>({visible: false, params: {}});

  const showModal = useCallback(
    (modalType: ModalType, animationType?: AnimationType, params?: any) => {
      setState({visible: true, params, type: modalType, animationType});
    },
    [],
  );

  const hideModal = useCallback(() => {
    setState({visible: false, params: {}});
  }, []);

  return (
    <ModalContext.Provider value={{...state, showModal}}>
      <BasicsModal
        visible={state.visible}
        onDismiss={hideModal}
        type={state.type as ModalType}
        animationType={state.animationType ?? 'fade'}
        params={state.params}
      />
      {children}
    </ModalContext.Provider>
  );
};

export default ModalProvider;

export const useModalContext = function () {
  return useContext(ModalContext);
};
